package cn.com.zaprk.jdbc;

import java.sql.*;

/**
 * @PackageName: cn.com.zaprk.jdbc
 * @ClassName: JDBC_08_Select
 * @Description: JDBC查询数据  DQL
 * @author: RZS
 * @date: 2021/10/20  18:07
 */
public class JDBC_08_Select {
    public static void main(String[] args) {

        Connection conn = null;
        Statement stat = null;
        ResultSet resultSet = null;
        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://192.168.80.142:3306/mydb2", "root", "root");
            // 3、创建Statement对象，执行sql对象
            stat = conn.createStatement();
            // 4、编写sql语句
            String sql = "select * from user";
            // 5、执行sql
            resultSet = stat.executeQuery(sql);
            // 6、获取结果
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id"));
                System.out.println(resultSet.getString("name"));
                System.out.println(resultSet.getString("pwd"));
                System.out.println(resultSet.getDouble("money"));
            }

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 7、关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
